// src/screens/VipScreen.js
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, ScrollView, Alert } from 'react-native';
import { useSelector } from 'react-redux';
import api from '../services/api';

const VipScreen = ({ navigation }) => {
  const userInfo = useSelector(state => state.user.userInfo);
  const [vipPackages, setVipPackages] = useState([]);
  const [selectedPackage, setSelectedPackage] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchVipPackages();
  }, []);

  const fetchVipPackages = async () => {
    try {
      const response = await api.getVipPackages();
      if (response.success) {
        setVipPackages(response.data);
      }
    } catch (error) {
      console.log('获取VIP套餐失败:', error);
    }
  };

  const handlePurchase = async () => {
    if (!selectedPackage) {
      Alert.alert('提示', '请选择一个VIP套餐');
      return;
    }

    setLoading(true);
    try {
      const response = await api.purchaseVip(selectedPackage.id);
      if (response.success) {
        Alert.alert('成功', 'VIP开通成功！');
        navigation.goBack();
      } else {
        Alert.alert('失败', response.message || '开通失败');
      }
    } catch (error) {
      Alert.alert('错误', '开通失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>VIP会员</Text>
        <Text style={styles.subtitle}>尊享更多特权</Text>
      </View>

      <View style={styles.userInfo}>
        <Text style={styles.diamondsText}>粉钻余额: {userInfo?.diamonds || 0}</Text>
        {userInfo?.isVip && new Date(userInfo.vipEndTime) > new Date() ? (
          <Text style={styles.vipStatus}>VIP有效期至: {new Date(userInfo.vipEndTime).toLocaleDateString()}</Text>
        ) : (
          <Text style={styles.vipStatus}>您还不是VIP会员</Text>
        )}
      </View>

      <Text style={styles.sectionTitle}>选择VIP套餐</Text>
      <View style={styles.packagesContainer}>
        {vipPackages.map((pkg) => (
          <TouchableOpacity
            key={pkg.id}
            style={[
              styles.packageCard,
              selectedPackage?.id === pkg.id && styles.selectedPackage
            ]}
            onPress={() => setSelectedPackage(pkg)}
          >
            <Text style={styles.packageName}>{pkg.name}</Text>
            <Text style={styles.packagePrice}>{pkg.price} 粉钻</Text>
            <View style={styles.benefitsContainer}>
              {pkg.benefits && pkg.benefits.map((benefit, index) => (
                <View key={index} style={styles.benefitItem}>
                  <Text style={styles.benefitText}>✓ {benefit}</Text>
                </View>
              ))}
            </View>
            <Text style={styles.packageDuration}>{pkg.durationDays}天有效期</Text>
          </TouchableOpacity>
        ))}
      </View>

      <TouchableOpacity
        style={styles.purchaseButton}
        onPress={handlePurchase}
        disabled={!selectedPackage || loading}
      >
        <Text style={styles.purchaseButtonText}>
          {loading ? '开通中...' : (selectedPackage ? `开通VIP (${selectedPackage.price}粉钻)` : '请选择套餐')}
        </Text>
      </TouchableOpacity>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    backgroundColor: '#fff',
    padding: 20,
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#000',
  },
  subtitle: {
    fontSize: 16,
    color: '#666',
    marginTop: 4,
  },
  userInfo: {
    backgroundColor: '#fff',
    padding: 16,
    margin: 16,
    borderRadius: 8,
    alignItems: 'center',
  },
  diamondsText: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#ff6b6b',
  },
  vipStatus: {
    fontSize: 16,
    color: '#666',
    marginTop: 8,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#000',
    paddingHorizontal: 16,
    marginBottom: 12,
  },
  packagesContainer: {
    paddingHorizontal: 16,
  },
  packageCard: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: '#e0e0e0',
  },
  selectedPackage: {
    borderColor: '#ff6b6b',
    borderWidth: 2,
  },
  packageName: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#000',
  },
  packagePrice: {
    fontSize: 18,
    color: '#ff6b6b',
    fontWeight: 'bold',
    marginVertical: 8,
  },
  benefitsContainer: {
    marginVertical: 8,
  },
  benefitItem: {
    paddingVertical: 2,
  },
  benefitText: {
    fontSize: 14,
    color: '#666',
  },
  packageDuration: {
    fontSize: 14,
    color: '#999',
    marginTop: 8,
  },
  purchaseButton: {
    backgroundColor: '#ff6b6b',
    padding: 16,
    margin: 16,
    borderRadius: 8,
    alignItems: 'center',
  },
  purchaseButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
  },
});

export default VipScreen;